<template>
  <div class="app-container" v-loading="formLoading">
    <el-form
      :model="postForm"
      :rules="rules"
      ref="postForm"
      label-width="220px"
      label-position="right"
    >
      <el-form-item label="讲师名称：" prop="name">
        <el-input v-model.trim="postForm.name" placeholder="请输入讲师名称" style="width: 420px"></el-input>
        <span class="color666">(建议6个汉字以内)</span>
      </el-form-item>
      <el-form-item label="讲师身份：">
        <el-input v-model="postForm.title" placeholder="请输入讲师身份" style="width: 420px"></el-input>
        <span class="color666">(建议15个汉字以内，如果想更多介绍讲师身份，请在对应课程简介中描述)</span>
      </el-form-item>
      <el-form-item label="讲师分成比例：">
        <el-input-number
          v-model="postForm.ratio"
          placeholder="请输入讲师的分成比例"
          style="width: 120px"
          controls-position="right"
        ></el-input-number>%
      </el-form-item>
      <el-form-item label="讲师身份绑定：">
        <el-input v-model="mobile" style="width:200px" placeholder="搜索手机号"></el-input>
        <el-input v-model="nickname" style="width:200px" placeholder="搜索用户名"></el-input>
        <el-button @click="searchUser()">搜索</el-button>
        <el-select v-model="postForm.userId" placeholder="请选择用户">
          <el-option
            v-for="item in userList"
            :key="item.userId"
            :label="item.nickname"
            :value="item.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="讲师头像(宽68*高68)：">
        <el-upload
          ref="upload"
          name="avatar"
          :action="imageUploadUrl"
          list-type="picture"
          :before-upload="handleBeforeUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :file-list="avatarList"
          :limit="1"
          :auto-upload="false"
          style="width: 420px">
          <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        </el-upload>
      </el-form-item>-->
      <el-form-item label="讲师头像(宽68*高68)：">
        <image-component class="fl" :image="postForm.avatar" :width="'68px'" :height="'68px'"></image-component>
        <el-button
          class="fl el-btn"
          size="small"
          icon="upload"
          style="bottom: 15px;margin-left: 40px;"
          @click="imagecropperShow=true"
        >更换图片</el-button>
        <image-cropper
          :width="68"
          :height="68"
          :url="imageUploadUrl"
          @close="closeImageCropper"
          @crop-upload-success="cropSuccess"
          langType="zh"
          :key="imagecropperKey"
          v-show="imagecropperShow"
        ></image-cropper>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-check" @click="submitForm">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import imageComponent from "@/components/imageComponent";
import ImageCropper from "@/components/ImageCropper";
import { getMemberList } from "@/api/member";
import { getLecturer, createLecturer, updateLecturer } from "@/api/lecturer";
const postForm = {
  name: null,
  title: null,
  avatar: " ",
  userId: ""
};

const rules = {
  name: [{ required: true, message: "请输入讲师名称", trigger: "blur" }]
};

export default {
  components: {
    imageComponent,
    ImageCropper
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      postForm: Object.assign({}, postForm),
      rules,
      formLoading: false,
      avatarList: [],
      imageUploadUrl: process.env.BASE_API + "/common/lecturers/imageUpload",
      imagecropperShow: false,
      imagecropperKey: 0,
      mobile: null,
      nickname: null,
      userList: []
    };
  },
  created() {
    this.initData();
  },
  methods: {
    searchUser() {
      getMemberList({
        currentPage: 1,
        page: 1,
        mobile: this.mobile,
        nickname: this.nickname
      }).then(res => {
        this.userList = res.data.data.users.data;
      });
    },
    initData() {
      if (this.isEdit) {
        const lecturerId = this.$route.params.id;
        getLecturer(lecturerId)
          .then(res => {
            this.postForm = res.data.data;
            if (this.postForm.avatar) {
              this.avatarList = [{ url: this.postForm.avatar }];
            }
          })
          .catch(err => {
            console.log(err);
          });
      }
    },
    handleCreate() {
      createLecturer(this.postForm)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          this.close();
        })
        .catch(err => {
          this.formLoading = false;
          console.log(err);
        });
    },
    handleUpdate() {
      const lecturerId = this.$route.params.id;
      updateLecturer(lecturerId, this.postForm)
        .then(res => {
          this.$notify({
            title: "提示",
            message: "提交成功!",
            type: "success"
          });

          this.close();
        })
        .catch(err => {
          this.formLoading = false;
          console.log(err);
        });
    },
    redirectTo() {
      this.$router.push({ name: "lecturers" });
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.formLoading = true;
          if (this.isEdit) {
            this.handleUpdate();
          } else {
            this.handleCreate();
          }
        } else {
          console.log("error submit!");
          return false;
        }
      });
    },
    // submitUpload() {
    //   this.$refs.upload.submit()
    // },
    // handleSuccess(response, file, fileList) {
    //   if (response.statusCode == 200) {
    //     this.postForm.avatar = response.data.imageUrl
    //     this.$message({
    //       message: '上传成功!',
    //       type: 'info'
    //     })
    //   } else {
    //     this.$message({
    //       message: '上传失败，请稍候再试!',
    //       type: 'info'
    //     })
    //   }
    // },
    // handleBeforeUpload(file) {
    //   const isImg = file.type == 'image/jpeg' || file.type == 'image/png'
    //   if (!isImg) {
    //     this.$message.warning('上传图片只能是 JPG 或 PNG 格式')
    //   }
    //   return isImg
    // },
    // handleRemove(file, fileList) {
    //   this.postForm.avatar = null
    // },
    // 图片裁剪
    closeImageCropper() {
      this.imagecropperShow = false;
    },
    cropSuccess(resData) {
      this.imagecropperShow = false;
      this.imagecropperKey = this.imagecropperKey + 1;
      this.postForm.avatar = resData.data.imageUrl;
    },
    close() {
      this.$store.dispatch("delVisitedViews", this.$route).then(views => {
        const latestView = views.slice(-1)[0];
        if (latestView) {
          this.$router.push({ name: "lecturers" }); // latestView.path
        } else {
          this.$router.push("/");
        }
      });
    }
  }
};
</script>
